/**
 * Created by levy on 2016/12/21
 */
import React from 'react'
import {connect} from 'react-redux'
import Select from 'react-select'
import Loading from './Loading'
import _ from 'lodash'
import Report from './BudgetReport'
import Header from './Header'


@connect(
    state => {
        return {
            budget: state.budget
        }
    }
)
export default class BudgetDetail extends React.Component {
    state = {
        queryParams: {
            //页维的选项值
        },
        selectYear: '2016年'
    }
    componentDidMount() {
        // TODO 请求有待优化
        this.props.dispatch({
            type: 'budget/fetchBudgetModule',
            moduleId: this.props.location.query.id
        })
        this.props.dispatch({ type: 'budget/fetchDims', moduleId: this.props.location.query.id })
        this.props.dispatch({ type: 'budget/fetchDimTitles' })
        this.props.dispatch({ type: 'budget/fetchFixedDimItems' })
    }
    componentWillUnmount() {
        this.props.dispatch({ type: 'budget/showReport', show: false })
    }
    render() {
        let loading = this.props.budget.loading

        return (
            <div className="budget-detail">
                <Header title={this.props.location.query.title}/>
                <div className="mui-content">
                    {
                        !loading && this.renderFixedDims()
                    }
                    {
                        !loading && this.renderDims()
                    }
                    <Report selectYear={this.state.selectYear}/>
                </div>
                {
                    <div className="fixed-wrapper">
                        <div className="fixed-content">
                            <div className="mui-button-row">
                                <button style={{width: '100%'}} className="mui-btn mui-btn-primary"
                                        onClick={this.refresh}>重置</button>
                            </div>
                        </div>
                    </div>
                }
                <Loading loading={this.props.budget.loading}/>
            </div>
        )
    }
    renderFixedDims = () => {
        let {queryParams} = this.state
        let {fixedDims, fixedDimItems} = this.props.budget

        return fixedDims.map(dim =>
            <div className="select-group" key={dim.ID}>
                <div className="select-label">{dim.FNAME}</div>
                <Select options={fixedDimItems[dim.ID]}
                        value={queryParams[dim.ID]}
                        onChange={option => this.changeQueryParams(dim.ID, option && option.value)}
                        inputProps={{readOnly: true}} />
            </div>
        )
    }
    renderDims = () => {
        let {queryParams} = this.state
        let {dims, dimItems} = this.props.budget

        const isDebug = location.hostname == 'localhost'

        return dims.map(dim => (
            <div className="select-group" key={dim.ID}>
                <div className="select-label">{dim.label}</div>
                <Select options={dimItems[dim.ID]}
                        value={queryParams[dim.ID]}
                        onChange={option => this.changeQueryParams(dim.ID, option && option.value)}
                        inputProps={{readOnly: !isDebug}} />
            </div>
        ))
    }
    changeQueryParams = (key, value) => {
        let {queryParams, selectYear} = this.state

        queryParams[key] = value

        this.setState({queryParams: queryParams, selectYear: '2016年'})
        
        // 加载报表逻辑
        let {dims, fixedDims} = this.props.budget,
            values = [],
            keys = [],
            body = {}

        if (dims.length + fixedDims.length == _.compact(_.values(queryParams)).length) {

            dims.map(dim => {
                keys.push('F' + dim.FCODE.toUpperCase())
                values.push(queryParams[dim.ID])
            })

            fixedDims.forEach(obj => body['F'+obj.FCODE.toUpperCase()] = queryParams[obj.ID])

            // fetch "data" data
            this.props.dispatch({
                type: 'budget/fetchReportData',
                moduleId: this.props.location.query.id,
                keys: keys.toString(),
                values: values.toString(),
                body: body
            })

            fixedDims.forEach(obj => {
                keys.push('F'+obj.FCODE.toUpperCase())
                values.push(queryParams[obj.ID])
            })

            // fetch struct data
            this.props.dispatch({
                type: 'budget/fetchReportStruct',
                moduleId: this.props.location.query.id,
                keys: keys.toString(),
                values: values.toString()
            })

        }

    }
    refresh = () => {
        this.setState({queryParams: {}})
        
        this.props.dispatch({ type: 'budget/showReport', show: false })
    }
    // 需求变动, 不用发起审批流程
    // submit() {
    //     let {location, budget: {dims} } = this.props
    //     let {queryParams} = this.state
    //
    //     let keys = [],
    //         values = []
    //
    //     dims.map(dim => {
    //         keys.push('F' + dim.FCODE.toUpperCase())
    //         values.push(queryParams[dim.ID])
    //     })
    //
    //     // 因为要用的是state里的数据, 就不写到saga里了
    //     mui.confirm('发起审批流程前请先保存数据，是否继续?', '提示', ['否', '是'], function (e) {
    //         if (e.index == 1) {
    //
    //             ajax({
    //                 url: '/workflow/api/v1/budget-audit',
    //                 contentType: 'application/json',
    //                 type: 'POST',
    //                 data: {
    //                     modId: location.query.id * 1,
    //                     map: {
    //                         [FCODE_YEAR]: queryParams[DIM_TYPE_YEAR] + '',
    //                         [FCODE_PERIOD]: queryParams[DIM_TYPE_PERIOD] + '',
    //                         [FCODE_VERSION]: queryParams[DIM_TYPE_VERSION] + '',
    //                     },
    //                     keys: keys.toString() || '',
    //                     values: values.toString() || '',
    //                 },
    //                 success(data) {
    //                     if (data.errCode) {
    //                         mui.alert(data.msg)
    //                     }
    //                     else
    //                         mui.alert('操作成功!')
    //                 }
    //             })
    //         }
    //         else
    //             console.debug('选择了否')
    //     })
    // }
}

